package com.insigma.business.common.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Objects;

public class JacksonUtil {

    private static final ObjectMapper OBJCET_MAPPER = new ObjectMapper();

    static {
        OBJCET_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public static ObjectMapper getObjectMapper() {
        return OBJCET_MAPPER;
    }

    public static <T> T formatStringValue(String taget, Class<T> clazz) {
        if (StringUtils.isBlank(taget)) {
            throw new RuntimeException("json解析参数为空");
        }
        if (Objects.isNull(clazz)) {
            throw new RuntimeException("json解析类型为空");
        }
        try {
            return OBJCET_MAPPER.readValue(taget, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T formatStringValue(String taget, TypeReference<T> typeReference) {
        if (StringUtils.isBlank(taget)) {
            throw new RuntimeException("json解析参数为空");
        }
        if (Objects.isNull(typeReference)) {
            throw new RuntimeException("json解析类型为空");
        }
        try {
            return OBJCET_MAPPER.readValue(taget, typeReference);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String formatObjToStr(Object obj) {
        if (Objects.isNull(obj)) {
            throw new RuntimeException("参数不能为null");
        }
        try {
            return OBJCET_MAPPER.writeValueAsString(obj);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
